const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: process.env.DB_HOST || "43.143.253.188",
  port: parseInt(process.env.DB_PORT || "3306", 10),
  user: process.env.DB_USER || "nextjs",
  password: process.env.DB_PASS || "yEAiRE2jcxTyRBy5",
  database: process.env.DB_NAME || "nextjs",
  charset: 'utf8mb4',
  timezone: '+08:00',
};

async function checkCasinoTables() {
  let connection;
  
  try {
    console.log('🔍 检查娱乐城相关表...');
    
    // 连接数据库
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功！');
    
    // 查看所有表
    console.log('\n📋 所有表:');
    const [tables] = await connection.execute("SHOW TABLES");
    tables.forEach(table => {
      const tableName = Object.values(table)[0];
      console.log(`  ${tableName}`);
    });
    
    // 检查娱乐城相关表
    const casinoTables = ['casino_dice_rounds', 'casino_chibi_rounds', 'casino_dice_bets', 'casino_chibi_bets'];
    
    for (const tableName of casinoTables) {
      console.log(`\n📋 检查表: ${tableName}`);
      try {
        const [exists] = await connection.execute(`SHOW TABLES LIKE '${tableName}'`);
        if (exists.length > 0) {
          console.log(`✅ 表 ${tableName} 存在`);
          
          // 查看表结构
          const [columns] = await connection.execute(`DESCRIBE ${tableName}`);
          console.log('  表结构:');
          columns.forEach(col => {
            console.log(`    ${col.Field}: ${col.Type} ${col.Null === 'NO' ? 'NOT NULL' : 'NULL'} ${col.Key ? `(${col.Key})` : ''}`);
          });
          
          // 查看数据量
          const [count] = await connection.execute(`SELECT COUNT(*) as count FROM ${tableName}`);
          console.log(`  数据量: ${count[0].count} 条记录`);
          
          // 如果是期数表，查看最新记录
          if (tableName.includes('_rounds')) {
            const [latest] = await connection.execute(`
              SELECT * FROM ${tableName} 
              ORDER BY id DESC 
              LIMIT 1
            `);
            if (latest.length > 0) {
              console.log('  最新记录:');
              const record = latest[0];
              Object.entries(record).forEach(([key, value]) => {
                console.log(`    ${key}: ${value}`);
              });
            }
          }
        } else {
          console.log(`❌ 表 ${tableName} 不存在`);
        }
      } catch (error) {
        console.log(`❌ 检查表 ${tableName} 时出错: ${error.message}`);
      }
    }
    
  } catch (error) {
    console.error('❌ 检查过程中发生错误:', error);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 执行检查
if (require.main === module) {
  checkCasinoTables()
    .then(() => {
      console.log('✅ 检查完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('❌ 检查失败:', error);
      process.exit(1);
    });
}

module.exports = { checkCasinoTables };
